const router = require('express').Router()
const {query} = require('../db')

router.get('/film/nowplayingcount', async (req, res) => {
  const sql = "select count(*) as total from films"
  let data = await query(sql)
  let pageCount = Math.ceil(data[0].total / 2)
  res.send({
    code: 0,
    msg: 'ok',
    data: {total: data[0].total}
  })
})

router.get('/film/nowplaying', async (req, res) => {
  const {page = 1} = req.query
  const pagesize = 2
  const offset = (page - 1) * pagesize

  let sql = `select * from films order by id desc limit ${offset},${pagesize}`
  let data = await query(sql)
  data = data.map(item => ({
    ...item,
    poster: 'http://localhost:9000' + item.poster
  }))
  // setTimeout(() => {
  // res.status(403).send({
  // res.status(204).send({
  res.send({
    code: 0,
    msg: 'ok',
    data
  })
  // }, 3000)
})

router.post('/film/nowplaying', async (req, res) => {
  let {name, director, category, type = 0, nation, premiereAt, runtime, synopsis, poster, info = ''} = req.body

  const sql = `insert into films 
  (name,director,category,type,nation,premiereAt,runtime,synopsis,poster,info) 
  values 
  ('${name}','${director}','${category}','${type}','${nation}', '${premiereAt}','${runtime}','${synopsis}','${poster}','${info}')`
  let ret = await query(sql)
  res.send({
    code: 0,
    msg: 'ok',
    data: {name, director, category, type, nation, premiereAt, runtime, synopsis, poster, info}
  })
})

module.exports = router
